from django.contrib.auth.backends import ModelBackend
from .models import User
from django.db.models import Q

class UsernameMobileAuthBackend(ModelBackend):
    """重写ＪＷＴ认证用户的后端，也就是重写ＪＷＴ查询用户的方式　增加手机号查询"""

    def authenticate(self, request, username=None, password=None, **kwargs):
        """增加手机号查询方式"""
        try:
            user = User.objects.get(Q(username=username) | Q(mobile =username))
            if user and user.check_password(password):
                return user
        except User.DoesNotExist:
            return None


def jwt_response_payload_handler(token,user,request):
    """重写ＪＷＴ的登陆后端生成响应数据的方法
    在token的基础之上，增加username和user_id作为响应字段"""
    return {
        'token':token,
        'username':user.username,
        'user_id':user.id
    }

